from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.mini.layers import mini_layers_controller
from app.models import CustomerUser, MiniLike
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.mini import *
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.utils.upload import upload_image,upload_file

mini_layers_router = APIRouter()
model_name = "圈层"



@mini_layers_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_mini_like_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    user_id = CTX_USER_ID.get()
    is_praise = 0
    q = Q(status=1)
    total, data = await mini_layers_controller.do_list(page=page, page_size=page_size, search=q)

    user_ids = {logs['user_id'] for logs in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}
    users_tx_dict = {user.id: user.avatar for user in users}

    for item in data:
        item["nickname"] = users_dict.get(item['user_id'], "游客")
        item["avatar"] = users_tx_dict.get(item['user_id'],'')
        item["picture"] = item['images'][0]['url']
        if user_id>0:
            is_praise = await MiniLike.filter(user_id=user_id).filter(type=2).filter(type_id=item['id']).count()
        item["is_praise"] = is_praise


    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_layers_router.post("/create", summary=f"创建{model_name}", dependencies=[DependCustomerAuth])
async def do_mini_like_create(
        data_in: MiniLayersCreate,
):
    user_id = CTX_USER_ID.get()
    data_in.user_id = user_id
    await mini_layers_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")


@mini_layers_router.get("/delete", summary=f"删除{model_name}", dependencies=[DependCustomerAuth])
async def do_mini_like_delete(
        data_id: int = Query(..., description="ID"),
):
    user_id = CTX_USER_ID.get()
    q = Q(user_id=user_id)
    q &= Q(id=data_id)
    await mini_layers_controller.do_delete(search=q)
    return Success(msg="删除成功")

@mini_layers_router.post("/file", summary="上传图片")
async def file_content(file: UploadFile):
    url = await upload_image(file,"mini/layers")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)